import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Layout,
  Menu,
  Avatar,
  Dropdown,
  Button,
  Card,
  Row,
  Col,
  Statistic,
  Typography,
  Space,
  Progress,
  List,
  Tag,
  message,
} from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  SearchOutlined,
  FileTextOutlined,
  BarChartOutlined,
  UserOutlined,
  LogoutOutlined,
  SettingOutlined,
  ArrowUpOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import type { MenuProps } from 'antd';

const { Header, Sider, Content } = Layout;
const { Title, Text } = Typography;

const Dashboard: React.FC = () => {
  const navigate = useNavigate();
  const [collapsed, setCollapsed] = useState(false);
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    totalKeywords: 0,
    optimizedKeywords: 0,
    averageAdoptionRate: 0,
    totalContent: 0,
  });

  // 检查登录状态
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (!token) {
      navigate('/login');
      return;
    }

    // 模拟数据加载
    setTimeout(() => {
      setStats({
        totalKeywords: 24,
        optimizedKeywords: 18,
        averageAdoptionRate: 0.75,
        totalContent: 156,
      });
      setLoading(false);
    }, 1000);
  }, [navigate]);

  const user = JSON.parse(localStorage.getItem('user') || '{}');

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    message.success('已安全退出登录');
    navigate('/login');
  };

  const userMenuItems: MenuProps['items'] = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
      onClick: handleLogout,
    },
  ];

  const menuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '仪表板',
    },
    {
      key: 'keywords',
      icon: <SearchOutlined />,
      label: '关键词管理',
    },
    {
      key: 'content',
      icon: <FileTextOutlined />,
      label: '内容管理',
    },
    {
      key: 'analytics',
      icon: <BarChartOutlined />,
      label: '监控分析',
    },
    {
      key: 'enterprise',
      icon: <UserOutlined />,
      label: '企业管理',
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '系统设置',
    },
  ];

  const optimizationRate = stats.totalKeywords > 0 
    ? (stats.optimizedKeywords / stats.totalKeywords) * 100 
    : 0;

  const recentActivities = [
    {
      id: '1',
      title: '添加新关键词',
      description: '添加了关键词"AI优化"',
      time: '刚刚',
      type: 'keyword',
    },
    {
      id: '2',
      title: '内容生成完成',
      description: '为关键词"机器学习"生成了新内容',
      time: '1小时前',
      type: 'content',
    },
    {
      id: '3',
      title: '分析报告完成',
      description: '本周优化效果分析报告已生成',
      time: '2小时前',
      type: 'analysis',
    },
  ];

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'keyword':
        return <SearchOutlined style={{ color: '#1890ff' }} />;
      case 'content':
        return <FileTextOutlined style={{ color: '#52c41a' }} />;
      case 'analysis':
        return <BarChartOutlined style={{ color: '#fa8c16' }} />;
      default:
        return null;
    }
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div
          style={{
            height: '64px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#fff',
            fontSize: '18px',
            fontWeight: 'bold',
            background: 'rgba(255,255,255,0.1)',
          }}
        >
          {collapsed ? 'GEO' : 'GEO Platform'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['dashboard']}
          items={menuItems}
          onClick={({ key }) => {
            if (key === 'keywords') {
              navigate('/keywords');
            } else if (key === 'content') {
              navigate('/content');
            } else if (key === 'analytics') {
              navigate('/analytics');
            } else if (key === 'enterprise') {
              navigate('/enterprise');
            } else if (key === 'settings') {
              navigate('/settings');
            }
          }}
        />
      </Sider>
      
      <Layout>
        <Header
          style={{
            padding: '0 24px',
            background: '#fff',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            boxShadow: '0 1px 4px rgba(0,21,41,.08)',
          }}
        >
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            style={{ fontSize: '16px', width: 64, height: 64 }}
          />
          
          <Dropdown
            menu={{ items: userMenuItems }}
            placement="bottomRight"
          >
            <Space style={{ cursor: 'pointer' }}>
              <Avatar
                size="small"
                icon={<UserOutlined />}
                style={{ backgroundColor: '#1890ff' }}
              />
              <span>{user?.username || '用户'}</span>
            </Space>
          </Dropdown>
        </Header>
        
        <Content
          style={{
            margin: '16px 24px 0',
            overflow: 'initial',
          }}
        >
          <div
            style={{
              padding: '24px',
              background: '#fff',
              borderRadius: '8px',
              minHeight: 'calc(100vh - 112px)',
            }}
          >
            <Title level={2} style={{ marginBottom: '24px' }}>
              欢迎回来，{user?.username}！
            </Title>
            
            {/* 统计卡片 */}
            <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
              <Col xs={24} sm={12} lg={6}>
                <Card loading={loading}>
                  <Statistic
                    title="关键词总数"
                    value={stats.totalKeywords}
                    prefix={<SearchOutlined />}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card loading={loading}>
                  <Statistic
                    title="已优化关键词"
                    value={stats.optimizedKeywords}
                    prefix={<ArrowUpOutlined />}
                    valueStyle={{ color: '#3f8600' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card loading={loading}>
                  <Statistic
                    title="平均采用率"
                    value={(stats.averageAdoptionRate * 100).toFixed(1)}
                    suffix="%"
                    prefix={<BarChartOutlined />}
                    valueStyle={{ color: stats.averageAdoptionRate >= 0.7 ? '#3f8600' : '#cf1322' }}
                  />
                </Card>
              </Col>
              <Col xs={24} sm={12} lg={6}>
                <Card loading={loading}>
                  <Statistic
                    title="内容总数"
                    value={stats.totalContent}
                    prefix={<FileTextOutlined />}
                  />
                </Card>
              </Col>
            </Row>

            <Row gutter={[16, 16]}>
              {/* 优化进度 */}
              <Col xs={24} lg={12}>
                <Card
                  title="优化进度"
                  loading={loading}
                >
                  <div style={{ marginBottom: '16px' }}>
                    <Text>关键词优化完成度</Text>
                    <Progress
                      percent={optimizationRate}
                      status={optimizationRate >= 80 ? 'success' : 'active'}
                      format={(percent) => `${percent?.toFixed(1)}%`}
                    />
                  </div>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Statistic
                        title="已优化"
                        value={stats.optimizedKeywords}
                        valueStyle={{ color: '#3f8600', fontSize: '20px' }}
                      />
                    </Col>
                    <Col span={12}>
                      <Statistic
                        title="待优化"
                        value={stats.totalKeywords - stats.optimizedKeywords}
                        valueStyle={{ color: '#cf1322', fontSize: '20px' }}
                      />
                    </Col>
                  </Row>
                </Card>
              </Col>

              {/* 快速操作 */}
              <Col xs={24} lg={12}>
                <Card title="快速操作" loading={loading}>
                  <Row gutter={[8, 8]}>
                    <Col span={24}>
                      <Card
                        size="small"
                        hoverable
                        style={{ cursor: 'pointer' }}
                        onClick={() => navigate('/keywords')}
                      >
                        <Card.Meta
                          avatar={<PlusOutlined />}
                          title="添加关键词"
                          description="快速添加需要优化的关键词"
                        />
                      </Card>
                    </Col>
                    <Col span={24}>
                      <Card
                        size="small"
                        hoverable
                        style={{ cursor: 'pointer' }}
                        onClick={() => navigate('/content')}
                      >
                        <Card.Meta
                          avatar={<FileTextOutlined />}
                          title="生成内容"
                          description="基于关键词生成优化内容"
                        />
                      </Card>
                    </Col>
                    <Col span={24}>
                      <Card
                        size="small"
                        hoverable
                        style={{ cursor: 'pointer' }}
                        onClick={() => navigate('/analytics')}
                      >
                        <Card.Meta
                          avatar={<BarChartOutlined />}
                          title="查看分析"
                          description="查看优化效果分析报告"
                        />
                      </Card>
                    </Col>
                  </Row>
                </Card>
              </Col>
            </Row>

            {/* 最近活动 */}
            <Row style={{ marginTop: '24px' }}>
              <Col span={24}>
                <Card
                  title="最近活动"
                  loading={loading}
                >
                  <List
                    itemLayout="horizontal"
                    dataSource={recentActivities}
                    renderItem={(item) => (
                      <List.Item>
                        <List.Item.Meta
                          avatar={getActivityIcon(item.type)}
                          title={
                            <Space>
                              {item.title}
                              <Tag color="blue">{item.time}</Tag>
                            </Space>
                          }
                          description={item.description}
                        />
                      </List.Item>
                    )}
                  />
                </Card>
              </Col>
            </Row>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default Dashboard;